/* socket.c
 * This file is part of the Tisa Project.
 * 
 * Authors: Cleiber Marques da Silva <cleiber.dev@gmail.com>
 *          Odilson Tadeu Valle <odilson@sj.cefetsc.edu.br>
 *
 * Tisa Project is free software; you can redistribute
 * it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; version 2 of
 * the License.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <netdb.h>
#include <string.h>

#include "socket.h"
#include "log.h"

int socket_init()
{
	return socket(PF_INET, SOCK_DGRAM, 0);
}

int create_destination(char *destination, int port, struct sockaddr_in *server)
{
	struct hostent *dest;
	struct in_addr address;

	if (inet_aton(destination, &address))
		dest = gethostbyaddr((char *)&address, sizeof(address), AF_INET);
	else
		dest = gethostbyname(destination);
									
	if (dest == NULL)
		return -1;
																		
	memset((char *) server, 0, sizeof(server));
	memcpy(&server->sin_addr, dest->h_addr_list[0], sizeof(server->sin_addr));
	server->sin_family = AF_INET;
	server->sin_port = htons(port);
					
	return 0;
}

void send_msg(int sock_fd, struct sockaddr_in server, char *msg)
{
		
	if (sendto(sock_fd, msg, strlen(msg) + 1, 0, (struct sockaddr *) &server, sizeof(server)) < 0 )	
		log_print(LOG_ERROR, "sendto failed!\n");
	return;
}


int recv_msg(int sock_fd, char *buffer)
{
	int bytes; 
	
	if ((bytes = recvfrom(sock_fd, buffer, BUFF_SIZE, 0, NULL, 0)) < 0) 
		log_print(LOG_ERROR, "recvfrom failed!\n");
	return bytes;
}
